package imsdk

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/http"
	"math/rand"
	"strconv"
)

type (
	BroadcastMsg struct {
		GroupId   string    `json:"GroupId"` // 群ID
		Random    int32     `json:"Random"`  // 随机数
		MsgBodies []MsgBody `json:"MsgBody"` // 内容
	}

	BroadcastApiFullRequest struct {
		GroupID string `json:"GroupId"`
		Random  int    `json:"Random"`
		MsgBody []struct {
			MsgType    string `json:"MsgType"`
			MsgContent struct {
				Text string `json:"Text"`
			} `json:"MsgContent,omitempty"`
			MsgContent0 struct {
				Index int    `json:"Index"`
				Data  string `json:"Data"`
			} `json:"MsgContent,omitempty"`
		} `json:"MsgBody"`
		CloudCustomData string `json:"CloudCustomData"`
		OfflinePushInfo struct {
			PushFlag    int    `json:"PushFlag"`
			Desc        string `json:"Desc"`
			Ext         string `json:"Ext"`
			AndroidInfo struct {
				Sound string `json:"Sound"`
			} `json:"AndroidInfo"`
			ApnsInfo struct {
				Sound     string `json:"Sound"`
				BadgeMode int    `json:"BadgeMode"`
				Title     string `json:"Title"`
				SubTitle  string `json:"SubTitle"`
				Image     string `json:"Image"`
			} `json:"ApnsInfo"`
		} `json:"OfflinePushInfo"`
	}

	BroadcastResp struct {
		ActionStatus  string `json:"ActionStatus"`
		ErrorInfo     string `json:"ErrorInfo"`
		ErrorCode     int    `json:"ErrorCode"`
		MsgTime       int    `json:"MsgTime"`
		MsgSeq        int    `json:"MsgSeq"`
		MsgDropReason string `json:"MsgDropReason"`
	}
)

// Broadcast 广播消息
func (s sdk) Broadcast(groupId int, msg []string) {
	url := s.BuildRestfulUrl("/group_open_http_svc/send_group_msg")
	random := rand.Int31()
	var msgBodies []MsgBody
	for _, m := range msg {
		msgBodies = append(msgBodies, MsgBody{
			MsgType:    "TIMCustomElem",
			MsgContent: MsgContent{Data: m, Ext: strconv.Itoa(groupId)},
		})
	}

	j, err := json.Marshal(BroadcastMsg{
		Random:    random,
		GroupId:   strconv.Itoa(groupId),
		MsgBodies: msgBodies,
	})
	if err != nil {
		global.Log.Errorf("broadcast unmasal:%v", err)
		return
	}
	r, err := http.HttpPost(url, string(j), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("Broadcast error: %v, result: %s", err, r)
		return
	}
}
func (s sdk) BroadcastInterfaceString(groupId string, sMsg string, nRetry int) error {
	url := s.BuildRestfulUrl("/group_open_http_svc/send_group_msg")
	random := rand.Int31()
	var msgBodies []MsgBody
	msgBodies = append(msgBodies, MsgBody{
		MsgType:    "TIMCustomElem",
		MsgContent: MsgContent{Data: sMsg, Ext: groupId},
	})
	j, err := json.Marshal(BroadcastMsg{
		Random:    random,
		GroupId:   groupId,
		MsgBodies: msgBodies,
	})
	//global.Log.Debugf("BroadcastInterfaceString :%+v,err:%v", string(j), err)
	if err != nil {
		global.Log.Errorf("Broadcast error: %v, %v", err, sMsg)
		return err
	}
	r, err := http.HttpPost(url, string(j), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("Broadcast error: %v, result: %s", err, r)
		if nRetry > 0 {
			return s.BroadcastInterfaceString(groupId, sMsg, nRetry-1) //有重试机会的话就递归进去再试
		} else {
			return err
		}

	}
	resp := BroadcastResp{}
	err = json.Unmarshal(r, &resp)
	global.Log.Infof("broadCastOk:group%s, %s,%+v", groupId, sMsg, resp)
	if err != nil {
		global.Log.Errorf("Broadcast error: %s", err)
		if nRetry > 0 {
			return s.BroadcastInterfaceString(groupId, sMsg, nRetry-1) //有重试机会的话就递归进去再试
		} else {
			return err
		}
	}

	if resp.ActionStatus != OKActionStatus || resp.ErrorCode != 0 {
		global.Log.Errorf("Broadcast error: %s, code : %d,groupId:%s", resp.ErrorInfo, resp.ErrorCode, groupId)
		if nRetry > 0 {
			return s.BroadcastInterfaceString(groupId, sMsg, nRetry-1) //有重试机会的话就递归进去再试
		} else {
			return fmt.Errorf(resp.ErrorInfo)
		}
	}
	//resp = BroadcastResp{}
	//err = json.Unmarshal(r, &resp)
	//if err != nil {
	//	global.Log.Errorf("Broadcast error: %s", err)
	//	return nil //这里虽然是出错了，但是已经请求成功了也
	//}
	return nil

}
func (s sdk) BroadcastInterface(groupId int, msg interface{}, nRetry int) error {
	marshal, _ := json.Marshal(msg)
	return s.BroadcastInterfaceString(cast.ToString(groupId), string(marshal), nRetry)
}

func (s sdk) BroadcastInterfaceGroupString(groupId string, msg interface{}, nRetry int) error {
	marshal, _ := json.Marshal(msg)
	return s.BroadcastInterfaceString(groupId, string(marshal), nRetry)
}
